package com.dk.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.dk.mapper.PersonRoleMapper;
import com.dk.mapper.RoleMenuMapper;
import com.dk.mapper.TRoleMapper;
import com.dk.pojo.RoleMenuExample;
import com.dk.pojo.TRole;
import com.dk.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

@Service
@org.springframework.stereotype.Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    private TRoleMapper tRoleMapper;

    @Autowired
    private RoleMenuMapper roleMenuMapper;

    @Autowired
    private PersonRoleMapper personRoleMapper;

    @Override
    public List<TRole> getInfo() {
        return tRoleMapper.getInfo();
    }

    public boolean addInfo(TRole role, Integer[] menuId) {
        try{
            //增加角色表返回主键id
            int i = tRoleMapper.insertInfoReturnId(role);
            //主键id
            Integer roleId = role.getRoleId();
            //增加中间表
            int i2 = roleMenuMapper.insertBatch(roleId,menuId);
            return true;
        }catch (Exception e){
            e.printStackTrace();
            throw e;
        }
    }

    @Override
    public boolean deleteById(Integer rid) {
        try {
            //删除角色表
            int i = tRoleMapper.deleteByPrimaryKey(rid);
            //删除角色菜单中间表
            RoleMenuExample rme = new RoleMenuExample();
            RoleMenuExample.Criteria criteria = rme.createCriteria();
            criteria.andRoleIdEqualTo(rid);
            roleMenuMapper.deleteByExample(rme);
            return true;
        }catch (Exception e){
            e.printStackTrace();
            throw e;
        }
    }

    @Override
    public TRole getInfoById(Integer roleId) {
        return tRoleMapper.selectByPrimaryKey(roleId);
    }

    @Override
    public Boolean updateInfo(TRole role, Integer[] menuId) {
        try{
            //修改角色信息
            int i = tRoleMapper.updateByPrimaryKeySelective(role);
            //通过rid删除对应的所有权限信息
            RoleMenuExample rme = new RoleMenuExample();
            RoleMenuExample.Criteria criteria = rme.createCriteria();
            criteria.andRoleIdEqualTo(role.getRoleId());
            roleMenuMapper.deleteByExample(rme);
            //增加对应的权限
            int i2 = roleMenuMapper.insertBatch(role.getRoleId(),menuId);
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public List<Integer> getUserRoleById(Integer pid) {
        List<Integer> list = personRoleMapper.getUserRoleById(pid);
        return list;
    }


}
